package com.xuanmiao.smsback.service.scheduled;

import com.panshi.hujin2.base.domain.page.Page;
import com.xuanmiao.smsback.dao.mapper.MessagePushHistoryMapper;
import com.xuanmiao.smsback.dao.mapper.UserAccountInfoMapper;
import com.xuanmiao.smsback.dao.mapper.UserInfoMapper;
import com.xuanmiao.smsback.dao.mapper.sms.MsgSendManageMapper;
import com.xuanmiao.smsback.dao.model.MessagePushHistoryDO;
import com.xuanmiao.smsback.dao.model.UserInfoDO;
import com.xuanmiao.smsback.dao.model.sms.MsgSendManageDO;
import com.xuanmiao.smsback.domain.qo.MsgSendManageQO;
import com.xuanmiao.smsback.domain.qo.UserInfoQO;
import com.xuanmiao.smsback.service.email.MailService;
import com.xuanmiao.smsback.service.email.event.SendEmailEvent;
import com.xuanmiao.smsback.service.email.event.SendEmailObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 账单提醒 每月1号9：00
 */
@Component
@JobHandler(value = "billNotifyService")
@Slf4j
public class BillNotifyService extends IJobHandler {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    private UserAccountInfoMapper userAccountInfoMapper;
    @Autowired
    MessagePushHistoryMapper messagePushHistoryMapper;

    @Autowired
    MsgSendManageMapper msgSendManageMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    @Qualifier("aliyunEmailServiceImpl")
    private MailService mailService;

    @Override
    public ReturnT<String> execute(String param) {
        // 查询所有的注册用户；
        List<UserInfoDO> userList = userInfoMapper.selectAll();

        LocalDate currentDate = LocalDate.now();

        LocalDate lastDate = currentDate.minusMonths(1);

        LocalDateTime start0 = lastDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay();
        LocalDateTime end0 = lastDate.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay();

        Date start = Date.from(start0.atZone(ZoneId.systemDefault()).toInstant());
        Date end = Date.from(end0.atZone(ZoneId.systemDefault()).toInstant());

        // 月度账单提醒
        userList.stream().forEach(user -> {
            if(user.getStatus() != 1){
                return ;
            }
            MsgSendManageQO msgSendManageQO = new MsgSendManageQO();
            msgSendManageQO.setCreateTimeStart(start);
            msgSendManageQO.setCreateTimeEnd(end);
            Page page = new Page();page.setIsPaging(false);
            msgSendManageQO.setPage(page);
            if(user.getIsMain()){
                msgSendManageQO.setConsumerId(user.getId());
            }else{
                msgSendManageQO.setCurrentConsumerId(user.getId());
            }

            List<MsgSendManageDO> list = msgSendManageMapper.queryByParam(msgSendManageQO);

            String userEmail = user.getEmail();
            if (CollectionUtils.isNotEmpty(list)) {
                Double sum = 0.0;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getRealFee() != null) {
                        sum += list.get(i).getRealFee();
                    }
                }
                MessagePushHistoryDO messagePushHistoryDO = new MessagePushHistoryDO();
                messagePushHistoryDO.setStatus(0);
                messagePushHistoryDO.setTitle("月度账单提醒");
                Date current = new Date();
                Calendar cal = Calendar.getInstance();
                cal.setTime(current);
                cal.add(Calendar.MONTH,-1);
                Date lastMonth = cal.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
                String text = MessageFormat.format("{0}账单消费总额{1}RMB", sdf.format(lastMonth), ""+sum);
                messagePushHistoryDO.setText(text);
                messagePushHistoryDO.setUserId(user.getId());
                messagePushHistoryMapper.insertSelective(messagePushHistoryDO);

//                if(!msgSendManage.getCurrentConsumerId().equals(msgSendManage.getConsumerId())){
//
//                }

                if(StringUtils.isNotBlank(userEmail)){
//                    SendEmailObject object = new SendEmailObject();
//                    object.setTo(Stream.of(userEmail).collect(Collectors.toList()));
//                    StringBuilder sb = new StringBuilder("");
//                    sb.append("尊敬的商户")
//                            .append(user.getBusinessNo())
//                            .append("\r\n")
//                            .append("您好")
//                            .append("\r\n")
//                            .append("您的账户")
//                            .append("【")
//                            .append(user.getAccountNo())
//                            .append("】")
//                            .append(sdf.format(lastMonth))
//                            .append("账单消费总额")
//                            .append(sum)
//                            .append("RMB");
//                    object.setContent(sb.toString());
                    StringBuilder sb = new StringBuilder("<html><body>");
                    String subject = "SMS"+sdf.format(lastMonth)+"账单";
                    sb.append("尊敬的商户")
                            .append(user.getBusinessNo())
                            .append("<br/>")
                            .append("您好")
                            .append("<br/>")
                            .append("您的账户")
                            .append("【")
                            .append(user.getAccountNo())
                            .append("】")
                            .append(sdf.format(lastMonth))
                            .append("账单消费总额")
                            .append(sum)
                            .append("RMB")
                            .append("</body></html>");

                    mailService.sendHtmlMail(userEmail,subject,sb.toString());
                }
            }
        });
        return ReturnT.SUCCESS;
    }
}
